﻿using Landpy.CruiseControlNet.ConfigurationSidekick.Resources;
using Landpy.CruiseControlNet.FacadeInterface.ConfigurationModule;

namespace Landpy.CruiseControlNet.ConfigurationSidekick.ConfigTreeModule
{
    class InternalSecurityHandler : UpdateChildrenNode
    {
        public override void UpdateChildrenNodes(ChildrenNodeContext childrenNodeContext)
        {
            var treeNodeIndentity = this.GetTreeNodeIndentity(childrenNodeContext);
            var treeNodesBuilder = this.GetTreeNodesBuilder(childrenNodeContext.CruiseControl);
            if (treeNodeIndentity.Type == TreeNodeType.InternalSecurity)
            {
                if (childrenNodeContext.ChangedValueKey == typeof(Permission).Name)
                {
                    var permissionsTreeNode = childrenNodeContext.SelectedNode.Nodes[Resource.TreeNode_Permissions];
                    permissionsTreeNode.Nodes.Clear();
                    if (childrenNodeContext.CruiseControl.InternalSecurity.Permissions != null)
                    {
                        foreach (var permission in childrenNodeContext.CruiseControl.InternalSecurity.Permissions)
                        {
                            treeNodesBuilder.BuildInternalPermissionNode(permission, permissionsTreeNode);
                        }
                    }
                    childrenNodeContext.SelectedNode.Expand();
                    permissionsTreeNode.Expand();
                }
                else if (childrenNodeContext.ChangedValueKey == typeof(SecurityUser).Name)
                {
                    var securityUsersTreeNode = childrenNodeContext.SelectedNode.Nodes[Resource.TreeNode_SecurityUsers];
                    securityUsersTreeNode.Nodes.Clear();
                    if (childrenNodeContext.CruiseControl.InternalSecurity.Permissions != null)
                    {
                        foreach (var user in childrenNodeContext.CruiseControl.InternalSecurity.Users)
                        {
                            treeNodesBuilder.BuildSecurityUserNode(user, securityUsersTreeNode);
                        }
                    }
                    childrenNodeContext.SelectedNode.Expand();
                    securityUsersTreeNode.Expand();
                }
            }
            else
            {
                this.Successor.UpdateChildrenNodes(childrenNodeContext);
            }
        }
    }
}
